package com.qunduikj.sjb.sdk.utils;

import android.support.v4.app.Fragment;
import android.text.TextUtils;
import com.litesuits.android.log.Log;
import com.litesuits.orm.db.assit.Checker;
import com.qunduikj.sjb.sdk.config.ApiConfig;
import com.qunduikj.sjb.sdk.model.enums.FileType;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通用的功能
 * 主要是java中字符串，集合操作
 * <p/>
 * Created by wangj on 15/8/19.
 */
public class GlobalUtil {
    static final String Tag = GlobalUtil.class.getSimpleName();
    static SimpleDateFormat dateFormat = new SimpleDateFormat();

    public static String formatTimeDefault(long timeMillis) {
        dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(new Date(timeMillis));
    }

    public static String formatTime(Date date, String pattern) {
        dateFormat.applyPattern(pattern);
        return dateFormat.format(date);
    }

    public static String formatTime(long time, String pattern) {
        dateFormat.applyPattern(pattern);
        return dateFormat.format(new Date(time));
    }

    public static int convertInt(Integer I, int defInt) {
        if (I != null) {
            return I;
        }
        return defInt;
    }

    public static void printFragmentState(Fragment... list) {
        if (list != null) {
            for (Fragment f : list) {
                Log.i(Tag, "fragment: ---------------------------> " + f);
                if (f != null) {
                    Log.i(Tag, "fragment  isVisible: " + f.isVisible() + "   isHidden: " + f.isHidden());
                    Log.i(Tag, "fragment  isAdded: " + f.isAdded() + "   isRemoving: " + f.isRemoving());
                    Log.i(Tag, "fragment  isResumed: " + f.isResumed() + "   isInLayout: " + f.isInLayout());
                    Log.i(Tag, "fragment  isDetached: " + f.isDetached() + "   isMenuVisible: " + f.isMenuVisible());
                    Log.i(Tag, "fragment  getUserVisibleHint: " + f.getUserVisibleHint());
                }
            }
        }
    }

    public static String formatRoadTitle(String tag, String address) {
        String str = new String("＃实时路况＃ [%s]，好友们，\"%s\"");
        try {
            str = String.format(str, tag, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 文件大小单位转换
     */

    public static String formatFileSize(long fileSize) {// 转换文件大小
        if (fileSize <= 0) {
            return "0.00B";
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "K";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * 获取文本
     */
    public static String getString(Object str) {
        if (str == null) {
            return "";
        } else {
            return str + "";
        }
    }

    /**
     * 电话号码显示加密
     */
    public static String getCryptPhoneNumber(String str) {
        String cryptNumber = str;
        try {
            cryptNumber = str.substring(0, 3) + " **** " + str.substring(str.length() - 4, str.length());
            return cryptNumber;
        } catch (Exception e) {
            return cryptNumber;
        }
    }

    /**
     * 电话号码格式化
     */
    public static String getFormatPhoneNumber(String str) {
        String formatNumber = str;
        try {
            formatNumber = str.substring(0, 3) + " " + str.substring(3, 7)
                    + " " + str.substring(str.length() - 4, str.length());
            return formatNumber;
        } catch (Exception e) {
            return formatNumber;
        }
    }

    /**
     * 将arraylist 中字符串，用逗号拼接成一个
     */
    public static String getStringForArray(List<String> stringList) {
        if (stringList == null || stringList.size() == 0) {
            return null;
        }

        StringBuilder sb = new StringBuilder();

        for (String s : stringList) {
            sb.append(s).append(",");
        }
        System.out.print(sb.toString());
        System.out.print(sb.substring(0, sb.length() - 1));
        // 将多出的一个逗号截去
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 毫秒转为日期
     *
     * @param time      毫秒
     * @param dateStyle 时间格式 可以为 例：“yyyy-MM-dd HH:mm:ss”
     */
    public static String millisecondToDate(Long time, String dateStyle) {
        DateFormat formatter = new SimpleDateFormat(dateStyle);
        return formatter.format(new Date(time));
    }


    /**
     * 日期转为毫秒
     */
    public static Long dateToMillisecond(String date, String datestyle) {
        SimpleDateFormat SimpleDateFormat = new SimpleDateFormat(datestyle);
        Long millionSeconds = null;//毫秒
        try {
            millionSeconds = SimpleDateFormat.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return millionSeconds;
    }


    /**
     * @param time
     * @return
     */
    public static String MillisecondToDateHasss(Long time) {
        return millisecondToDate(time, "yyyy-MM-dd HH:mm:ss");
    }

    //行驶距离的显示形式
    public static String getRouteMiDes(double mi) {
        //        X<1W时，如1234，则显示：跑了1234公里     赚了1234元
        //        X>=1W时，第三位四舍五入，如12345，则显示，跑了1.2w公里    赚了1.2w元
        //        如12891，则显示，跑了1.3w公里    赚了1.3w元
        double oneGL = 1000;
        DecimalFormat format = new DecimalFormat("0.00");
        if (mi < oneGL) {
            return format.format(mi) + " 米";
        } else if (mi < 10000 * oneGL) {
            return format.format(mi / 1000) + " 公里";
        } else {
            float w = (float) mi / 1000 / 10000;
            return format.format(w) + " 万公里";
        }
    }

    //行驶距离的显示形式
    public static String getTimeDes(long timeMillis) {
        //        1年3天5小时6分钟12秒
        int seconds = (int) (timeMillis / 1000);
        int minute = seconds / 60;
        int hour = minute / 60;
        int day = hour / 24;
        int year = day / 365;

        seconds = seconds % 60;
        minute = minute % 60;
        hour = hour % 24;
        day = day % 365;

        String des = "";
        if (year != 0) {
            des += year + "年 ";
        }
        if (day != 0) {
            des += day + "天 ";
        }
        if (hour != 0) {
            des += hour + "小时 ";
        }
        if (minute != 0) {
            des += minute + "分钟 ";
        }
        if (seconds != 0) {
            des += seconds + "秒 ";
        }
        return des;
    }

    //钱的显示形式
    public static String getRouteMoney(double money) {
        //        X<1W时，如1234，则显示：跑了1234公里     赚了1234元
        //        X>=1W时，第三位四舍五入，如12345，则显示，跑了1.2w公里    赚了1.2w元
        //        如12891，则显示，跑了1.3w公里    赚了1.3w元
//        double oneWan = 10000;
//        DecimalFormat format = new DecimalFormat("0.00");
//        if (money < oneWan) {
//            return format.format(money) + " 元";
//        } else {
//            float w = (float) money / 10000;
//
//            return format.format(w) + " 万元";
//        }
        //true有单位元，false没有单位
        return getRouteMoney(money, true);
    }

    public static String getRouteMoney(double money, boolean flag) {
        double oneWan = 10000;
        DecimalFormat format = new DecimalFormat("0.00");
        if (money < oneWan) {
            String m = format.format(money);
            if (flag)
                return m + " 元";
            return m;
        } else {
            float w = (float) money / 10000;
            String m = format.format(w);
            if (flag)
                return m + " 万元";
            return m + "万";
        }
    }


    public static String getMoney(Double money) {
        DecimalFormat format = new DecimalFormat("0.00");
        String m = format.format(money);
        return m;
    }

    //. .0 .00 .00000
    //对于钱的控制和判断   不能大于百万，小数点前边7位数  小数点后2位
    // gudge 0:正确， 1：数据过大， 2：格式不正确
    public static Map<String, Object> judgeMoney(String money) {
        Map<String, Object> map = new HashMap<>();
        //判断money是否为空
        if (Checker.isEmpty(money)) {
            map.put("gudge", false);
            map.put("content", Double.parseDouble(money));
            return map;
        }

        //判断点 . .0 .00 .00000
        if (money.startsWith(".")) {
            if (money.length() == 1 || money.length() > 3 ||
                    money.equals(".0") || money.equals(".00")) {
                map.put("gudge", 2);
                map.put("content", money);
                return map;
            }
        }

        //判断是否存在小数点 等于-1是没有小数点的并且小于8位数字以下格式大小OK的
        int num = money.indexOf(".");
        if (num == -1) {
            if (money.length() < 9) {
                map.put("gudge", 0);
                map.put("content", Double.parseDouble(money));
                return map;
            } else {
                //错误提示  数据过大
                map.put("gudge", 1);
                map.put("content", Double.parseDouble(money));
                return map;
            }
        } else {
            //输入的字符串存在小数点  判断小数点小数部分是否大于2 整数部分是否大于7位
            String f = money.substring(0, num);  //整数部分
            String s = money.substring(num + 1, money.length());  //小数部分
            if (s.length() > 2 || f.length() > 8) {
                map.put("gudge", 2);
                map.put("content", Double.parseDouble(money));
                return map;
            }
            map.put("gudge", 0);
            map.put("content", Double.parseDouble(money));
            return map;
        }
    }


    /**
     * @param state
     * @param address
     * @return
     */
    public static String getMarkTitleForStateAndAddress(int state, String address) {
        String title = "";
        switch (state) {
            case 1:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［加油］</font>,我的车,我来爱～";
                break;
            case 2:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［吃香喝辣］</font>,速度来围观～";
                break;
            case 3:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［修车保养］</font>,我的车,我来爱～";
                break;
            case 4:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［就寝］</font>,围观的不用～";
                break;

            case 5:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［休闲娱乐］</font>,速度来,一起happy~";
                break;
            case 6:
                title = "#标记＃ 好友们,“" + address + "“,可以<font color=#A38354>［停车］</font>,<font color=#A38354>［停车］</font>,<font color=#A38354>［停车］</font>,重要的事情说三遍～";
                break;
        }

        return title;
    }

    /**
     * @param mail
     * @return
     */
    public static String getNickByMail(String mail) {
        String nick = mail;
        try {
            nick = nick.split("@")[0];
        } catch (Exception e) {
            return nick;
        }
        return nick;
    }

    /**
     * 替换文本中的表情字符
     */
    public static String replaceEmojiCharacter(String msg) {
        try {
            char[] chars = msg.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (isEmojiCharacter(chars[i])) {
                    chars[i] = ' ';
                }
            }
            msg = new String(chars);
        } catch (Exception e) {
            Log.e(e.toString());
            return msg;
        }
        return msg;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint >= 0xD83C && codePoint <= 0xDFFF);
    }


    public static String getIntegralPointFormat(String text, String point) {
        return String.format(text, point);
    }

    /**
     * 获取当前天 零点时间
     * 例：2016-10-25
     * 返回  1445788800000
     */
    public static long getCurrentTime() {
        long currentTime = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
            String defaultEndDate = sdf.format(new Date()); //格式化当前时间
            currentTime = sdf.parse(defaultEndDate).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return currentTime;
    }


    /**
     * 获取文件的时间目录
     *
     * @return
     */
    public static String getCurrentFilePathByDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); //设置时间格式
        return sdf.format(new Date()); //格式化当前时间;
    }

    public static String getCurrentData() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); //设置时间格式
        return sdf.format(new Date()); //格式化当前时间;
    }


    /**
     * 得到本月的第一天
     */
    public static long getMonthFirstDay() {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)); //当前月
        cal.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String s2 = sdf1.format(cal.getTime());
        try {
            return sdf1.parse(s2).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 得到本月的最后一天最后一秒
     */
    public static long getMonthLastDay() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);  //下个月
            calendar.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            String s = sdf.format(calendar.getTime());
            return sdf.parse(s).getTime() - 1;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }


    public static Double getDoubleForString(String txt) {
        return (!TextUtils.isEmpty(txt) ? Double.parseDouble(txt) : 0);
    }

    public static String getDoubleFormat(Object o) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(new BigDecimal(getString(o)));
    }

    public static void main(String[] args) {

       /* System.out.println(getRouteMiDes(-23));
        System.out.println(getRouteMiDes(0));
        System.out.println(getRouteMiDes(2));
        System.out.println(getRouteMiDes(1000));
        System.out.println(getRouteMiDes(9999));
        System.out.println(getRouteMiDes(102034));
        System.out.println(getRouteMiDes(10000234234234d));*/

       /* System.out.println(getRouteMoney(-12));//-12元
        System.out.println(getRouteMoney(0));//0元
        System.out.println(getRouteMoney(2));//2元
        System.out.println(getRouteMoney(9999));//9999元
        System.out.println(getRouteMoney(100050));//10.0万元
        System.out.println(getRouteMoney(20007493828d));//2000749.4万元*/

        //        getStringForArray(getlist());
        //        System.out.println(getCryptPhoneNumber("18987773456"));
        //        System.out.println(formatRoadTitle("路堵", "浙江省杭州市文三路中小企业大厦"));
        //        System.out.println(getFormatPhoneNumber("18987773456"));
        //        System.out.print(getNickByMail("wangj@qunduikj.com"));
        //        System.out.print(getDateFolderPathByFileType(FileType.Voice));
        //        System.out.println(getIntegralPointFormat("+%s\n积分",5+""));

//        System.out.println(getCurrentFilePathByDate());
//        System.out.println(getCurrentData());
//        System.out.println(getVoicePreFixName("142", FileType.Voice));
//        System.out.println(getAvatarPreFixName("142", FileType.Images, FileType.Avatar));
//        System.out.println(getArticlePreFixName("142", FileType.Images, FileType.Article));

    }

}
